﻿namespace NoIdeaIoc;
internal class EmitHelper
{
    /// <summary>
    /// Emit调用方法
    /// </summary>
    /// <param name="myIL"></param>
    /// <param name="method"></param>
    public static void EmitCall(ILGenerator myIL, MethodInfo method)
    {
        if (method.IsSpecialName || ((method.IsAbstract || method.IsVirtual) && !method.IsFinal && !method.ReflectedType.IsSealed))
        {
            myIL.Emit(OpCodes.Callvirt, method);
        }
        else
        {
            myIL.Emit(OpCodes.Call, method);
        }
        /*
        if (method.IsVirtual)
            myIL.Emit(OpCodes.Callvirt, method);
        else
            myIL.Emit(OpCodes.Call, method);
        //*/
    }
    public static string GetFullName(Type type)
    {
        return GetFullName(type.FullName);
    }
    public static string GetFullName(string typeFullName)
    {
        var bytes = Encoding.UTF8.GetBytes(typeFullName);
        using (var md5 = MD5.Create())
        {
            return BinaryToHex(md5.ComputeHash(bytes));
        }
    }
    /// <summary>
    /// 二进制转换为字符串(大写)
    /// <para>16进制</para>
    /// </summary>
    /// <param name="bytes"></param>
    /// <param name="isHex">是否16进制表示</param>
    /// <returns></returns>
    public static string BinaryToHex(byte[] bytes, bool isHex = false)
    {
        if (bytes == null || bytes.Length == 0)
            return string.Empty;
        var builder = new System.Text.StringBuilder();
        if (isHex)
        {
            builder.Append("0x");
        }
        for (int i = 0; i < bytes.Length; i++)
        {
            var thisByte = bytes[i];
            builder.Append(NibbleToHex((byte)(thisByte >> 4)));
            builder.Append(NibbleToHex((byte)(thisByte & 0xf)));
            //hex[2 * i] = NibbleToHexLower((byte)(thisByte >> 4)); // high nibble
            //hex[2 * i + 1] = NibbleToHexLower((byte)(thisByte & 0xf)); // low nibble
        }
        return builder.ToString();
    }
    static char NibbleToHex(byte nibble, char aChar = 'A')
    {
        return (char)((nibble < 10) ? (nibble + '0') : (nibble - 10 + aChar));
    }
}